package com.bulemobi.activity.Ac_CarService;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.*;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.overlayutil.PoiOverlay;
import com.google.gson.Gson;
import com.bulemobi.adapter.DriverAdapter;
import com.bulemobi.bean.AiDaiJiaBean;
import com.bulemobi.data.DataCentre;
import com.bulemobi.net.tsz.afinal.FinalHttp;
import com.bulemobi.net.tsz.afinal.annotation.view.ViewInject;
import com.bulemobi.net.tsz.afinal.core.AsyncTask;
import com.bulemobi.net.tsz.afinal.http.AjaxCallBack;
import com.bulemobi.net.tsz.afinal.http.AjaxParams;
import com.bulemobi.urlCentre.UrlCentre;
import com.bulemobi.util.MD5Util;
import com.bulemobi.view.BaseActivity;
import com.bulemobi.view.titleView.ActionBarView;
import com.jsyh.hcb.R;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

/**
 * Created by 武 on 2014/9/23 0023.
 * 代驾服务
 */
public class Ac_ReplaceDriver extends BaseActivity implements View.OnClickListener {
    @ViewInject(id = R.id.tv_nearByDriver)
    TextView tv_nearByDriver;
    @ViewInject(id = R.id.actionBar)
    ActionBarView actionBarView;
    private MapView mapView = null;
    private OverlayOptions options;
    private BaiduMap baiduMap;
    private LocationClient mLocationClient = null;
    private BDLocationListener myListener = new MyLocationListener();
    private boolean isFirstLoc = true;
    @ViewInject(id = R.id.sildiing)
    LinearLayout sildiing;
    private String imei;
    public static ArrayList<AiDaiJiaBean> aiDaiJiaBeans;
    @ViewInject(id = R.id.lv_nearInfo)
    ListView lv_nearInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_nearby_main);
        sildiing.setVisibility(View.GONE);
        initView();
        initBaiduMap();
        imei = getIMEI(this);
        Log.d("OnCreate", imei);
    }

    /**
     * 初始化自己的地理位置
     * 和搜索附近司机的位置
     */
    String stri;
    byte[] bytes;
    HttpPost httpPost;
    HttpClient client;
    String result;

    private void initData(LatLng latLng) {
        httpPost = new HttpPost(UrlCentre.ADJ_BASEURL);
        String la = latLng.latitude + "";
        String lo = latLng.longitude + "";
        String latLngMD5 = "";
        try {
            latLngMD5 = MD5Util.encodeByMD5(la + lo + "aidaijia");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        stri = "1201|" + la + "|" + lo + "|3fe5d0205970e8a732686c7cc2e74745|A00000389528060|" + latLngMD5;
        Log.d("Ac_replace", stri);
        bytes = new byte[0];
        client = new DefaultHttpClient();
        AsyncTask task = new AsyncTask() {
            @Override
            protected Object doInBackground(Object[] params) {
                try {
                    bytes = stri.getBytes("UTF-8");
                    ByteArrayInputStream bs = new ByteArrayInputStream(bytes, 0, bytes.length);
                    HttpEntity entity = new InputStreamEntity(bs, bytes.length);
                    httpPost.setEntity(entity);
                    HttpResponse response = client.execute(httpPost);
                    result = EntityUtils.toString(response.getEntity(), "UTF-8");
                    Log.d("DOINBACKGROUND", result);
                    bs.close();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Object o) {
                if (aiDaiJiaBeans != null && aiDaiJiaBeans.size() != 0) {
                    aiDaiJiaBeans.clear();
                }
                try {
                    JSONArray array = new JSONArray(result);
                    aiDaiJiaBeans = new ArrayList<AiDaiJiaBean>();
                    for (int i = 0; i < array.length(); i++) {
                        AiDaiJiaBean bean;
                        bean = new Gson().fromJson(array.getJSONObject(i).toString(), AiDaiJiaBean.class);
                        aiDaiJiaBeans.add(bean);
                        initDriverList();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
                super.onPostExecute(o);
            }
        };
        task.execute();
    }

    private void initDriverList() {
        DriverAdapter adapter = new DriverAdapter(this, aiDaiJiaBeans, "Rep", getIMEI(this));
        lv_nearInfo.setAdapter(adapter);
    }

    private void requestHttp(String url, AjaxParams params) {
        FinalHttp http = new FinalHttp();
        http.post(url, params, new AjaxCallBack<Object>() {
            @Override
            public void onStart() {
                showProgressDialog();
                super.onStart();
            }

            @Override
            public void onSuccess(Object o) {
                closeProgressDialog();
                super.onSuccess(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                closeProgressDialog();
                showToastShort(getResources().getString(R.string.error_no_net));
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    private void initView() {
        actionBarView.title.setText("代驾服务");
    }

    @Override
    public void onClick(View v) {

    }


    private void requestLocation() {
        if (mLocationClient != null && mLocationClient.isStarted()) {
            mLocationClient.requestLocation();
        } else {
            Log.d("LocSDK4", "locClient is null or not started");
        }
    }


    @Override
    protected void onDestroy() {
        mLocationClient.stop();
        // 关闭定位图层
        baiduMap.setMyLocationEnabled(false);
        mapView.onDestroy();
        mapView = null;
        mLocationClient.unRegisterLocationListener(myListener);
        super.onDestroy();
    }

    private void initBaiduMap() {
        mapView = (MapView) findViewById(R.id.map);
        mLocationClient = new LocationClient(this);     //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        baiduMap = mapView.getMap();
        baiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        //开启交通图
//        baiduMap.setTrafficEnabled(true);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(60 * 1000);
        option.setAddrType("all");
        mLocationClient.setLocOption(option);
        mLocationClient.start();
        requestLocation();
    }

    @Override
    protected void onPause() {
        mapView.onPause();
        super.onPause();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        mapView.onResume();
        super.onResume();
    }


    class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(final BDLocation location) {
            if (location == null) {
                return;
            }
            DataCentre.address = location.getAddrStr();
            closeProgressDialog();
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                            // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            baiduMap.setMyLocationData(locData);

            LatLng ll = new LatLng(location.getLatitude(),
                    location.getLongitude());
            MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
            BitmapDescriptor bitmap = BitmapDescriptorFactory
                    .fromResource(R.drawable.zb);
            options = new MarkerOptions().position(ll).icon(bitmap);
            baiduMap.addOverlay(options);
            baiduMap.animateMapStatus(u);
            initData(ll);
            BaiduMap.OnMarkerClickListener listener = new BaiduMap.OnMarkerClickListener() {
                /**
                 * 地图 Marker 覆盖物点击事件监听函数
                 * @param marker 被点击的 marker
                 */
                public boolean onMarkerClick(Marker marker) {

                    return false;
                }
            };
            baiduMap.setOnMarkerClickListener(listener);
        }

        @Override
        public void onReceivePoi(BDLocation bdLocation) {

        }
    }

    private class MyPoiOverlay extends PoiOverlay {
        public MyPoiOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public boolean onPoiClick(int index) {
            super.onPoiClick(index);
            return true;
        }
    }

}
